package com.example.excel.base;
import android.view.View;
import android.view.ViewGroup;

import com.example.excel.utils.Utils;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by WYJ on 2020/7/30.
 */
public abstract class BaseRecyclerViewAdapter<T> extends RecyclerView.Adapter<CommonViewHolder<T>> {
    public CommonCallback<Object> mListener;

    public List<T> mData;

    public BaseRecyclerViewAdapter(List<T> data) {
        if(data == null){
            mData = new ArrayList<>();
        } else {
            mData = data;
        }
    }

    public BaseRecyclerViewAdapter() {
        mData = new ArrayList<>();
    }

    public List<T> getData() {
        return mData;
    }

    public void setData(List<T> mData) {
        if (mData == null) {
            this.mData.clear();
        } else {
            this.mData = mData;
        }
        notifyDataSetChanged();
    }

    public void addData(T t) {
        this.mData.add(t);
        notifyDataSetChanged();
    }

    public void addAllData(List<T> ts) {
        if (!Utils.isEmpty(ts)) {
            this.mData.addAll(ts);
            notifyDataSetChanged();
        }
    }

    @NonNull
    @Override
    public CommonViewHolder<T> onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return CommonViewHolder.get(parent.getContext(), parent, layoutId(viewType));
    }

    @Override
    public void onBindViewHolder(CommonViewHolder<T> holder, final int position) {
        holder.setBinding(variableId(), mData.get(position));
        convert(holder, mData.get(position), position);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mListener != null){
                    mListener.onResult(mData.get(position), position);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return mData == null || mData.isEmpty() ? 0 : mData.size();
    }

    protected abstract int layoutId(int viewType);

    protected abstract int variableId();

    protected void convert(CommonViewHolder<T> holder, final T entity, int position) {

    }

    public void setListener(CommonCallback<Object> mListener) {
        this.mListener = mListener;
    }

    public CommonCallback<Object> getListener() {
        return mListener;
    }
}
